package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class FtpTestWidget extends GeneralTestWidget {

    private Activity ctx;
    private FtpTestManager ftm;
    private LinearLayout ftpTestChartLayout;
    private Button backBtn;
    private Button btnRetest;
    private ScrollView scrView;
    private LinearLayout ftpTestDetail;
    private String localFilePath = Environment.getExternalStorageDirectory() + "/ftptest/";
    private String remotePath = "/";
    private String fileName = "ftp_test.png";

    private static final int COUNT = 3;
    private static final String TAG = "FtpTest";
    private int testedTimes;
    private String ftpFileName;
    private Task task;
    private Handler ftpTestHandler;

    public FtpTestWidget(Activity context) {
        super(context);
        this.ctx = context;
        inflate(ctx, R.layout.ftp_test_widget, this);
        ftpTestChartLayout = (LinearLayout) this.findViewById(R.id.ftpTestChartLayout);
        backBtn = (Button) this.findViewById(R.id.ftp_test_btnback);
        scrView = (ScrollView) this.findViewById(R.id.ftp_test_ScrView);
        ftpTestDetail = (LinearLayout) this.findViewById(R.id.ftp_test_detail);
        btnRetest = (Button) findViewById(R.id.btn_ftp_retest);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                back(ctx);
            }
        });
        btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                FtpTestWidget aw = new FtpTestWidget(ctx);
//                ctx.setContentView(aw);
//                aw.statFtpTest();
                if (null != ftpFileName) {
                    new UploadResultTask().execute();
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
            }
        });
        ftpTestHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.FTP_UPLOAD_DONE:
                    updateUploadProgress();
                    break;
                case MessageWhat.FTP_DOWNLOAD_DONE:
                    updateDownloadProgress();
                    break;
                case MessageWhat.DONE:
                    updateTestResult();
                    drawLineChart();
                    dismissProgressDialog();
                    break;
                case MessageWhat.FTP_CONNECT_TIMEOUT:
                    dismissProgressDialog();
                    showMessage(ctx, "FTP连接超时.");
                    break;
                case MessageWhat.NETWORK_INVALID:
                    dismissProgressDialog();
                    showMessage(ctx, "无法连接至因特网.");
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissProgressDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissProgressDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                }
            }
        };

        ftm = new FtpTestManager(localFilePath, remotePath, fileName);
        ftm.setHandler(ftpTestHandler);
        task = new Task();
    }

    private void initTestData() {
        String path = "cc/ufinity/networkdiagnose/widget/ftp_test.png"; 
        InputStream is = ctx.getClassLoader().getResourceAsStream(path); 
        // FileInputStream fis = new FileInputStream(is);

        try {
            ftm.setFileSize(is.available());
            File f = new File(localFilePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            FileOutputStream os = new FileOutputStream(localFilePath + fileName);
            byte[] buffer = new byte[512];
            int ch = -1;
            while ((ch = is.read(buffer)) != -1) {
                os.write(buffer, 0, ch);
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateUploadProgress() {
        testedTimes++;
        this.setDialogProgress(testedTimes);
        DecimalFormat df = new DecimalFormat("#");
        float uploadSpeed = ftm.getCurrentUpSpeed();
        int time = ftm.getCurrentTimes();
        StringBuffer sb = new StringBuffer();
        sb.append("第").append(time).append("次上传速度为：").append(df.format(uploadSpeed));
        sb.append("KB/S");
        TextView tv = new TextView(ctx);

        tv.setTextSize(12);
        tv.setText(sb.toString());
        ftpTestDetail.addView(tv);
        ftm.setTesting(false);
        setScrollViewDown(scrView);
    }

    private void updateDownloadProgress() {
        testedTimes++;
        this.setDialogProgress(testedTimes);
        DecimalFormat df = new DecimalFormat("#");
        float dwSpeed = ftm.getCurrentDwSpeed();
        int time = ftm.getCurrentTimes();
        StringBuffer sb = new StringBuffer();
        sb.append("第").append(time).append("次下载速度为：").append(df.format(dwSpeed));
        sb.append("KB/S");
        TextView tv = new TextView(ctx);
        tv.setTextSize(12);
        tv.setText(sb);
        ftpTestDetail.addView(tv);
        ftm.setTesting(false);
        setScrollViewDown(scrView);
    }

    private void updateTestResult() {
        DecimalFormat df = new DecimalFormat("#");
        float totalUpSpeed = ftm.getTotalUpSpeed();
        float totalDwSpeed = ftm.getTotalDwSpeed();
        int frequency = ftm.getFrequency();
        StringBuffer s = new StringBuffer();
        s.append("总次数:").append(frequency * 2);
        s.append(" 平均上传速度：").append(df.format(totalUpSpeed / frequency)).append(" kb/s");
        s.append(" 平均下载速度：").append(df.format(totalDwSpeed / frequency)).append(" kb/s");
        ;
        TextView tv = new TextView(ctx);
        tv.setTextColor(Color.CYAN);
        tv.setTextSize(13);
        tv.setText(s);
        ftpTestDetail.addView(tv);
        setScrollViewDown(scrView);

        task.testCount = frequency;
        FTPTask ftpTask = task.newFTPTask(null);
        ftpTask.upRate = df.format(totalUpSpeed / frequency);
        ftpTask.downRate = df.format(totalDwSpeed / frequency);
        ArrayList<FTPTask> tasks = new ArrayList<FTPTask>(1);
        tasks.add(ftpTask);
        task.ftpTasks = tasks;
        task.endTime = StringUtils.getDateTime();
        

    }

    public void statFtpTest() {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            showProgressDialog(ctx, "正在进行FTP测试...", COUNT * 2);
            int type = NetworkManager.detectNetworkConnectivity(ctx);
            if (type == -1) {
                sendMsg(MessageWhat.NETWORK_INVALID, ftpTestHandler);
            } else {
                initTask(task, ctx, type);
                new Thread() {
                    public void run() {
                        initTestData();
                        if (ftm.login(ftp.address, ftp.port, ftp.userName, ftp.password)) {
                            task.startTime = StringUtils.getDateTime();
                            ftm.startFtpUpTest(COUNT);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                Log.e(TAG, "FTP测试线程等待出错：", e);
                            }
                            ftm.startFtpDwTest(COUNT);
                        } else {
                            ftm.sendMsg(MessageWhat.FTP_CONNECT_TIMEOUT);
                        }
                    }
                }.start();
            }
        }
    }

    private void drawLineChart() {
        // ftm.logout();
        ChartManager cm = new ChartManager(ctx, 5, 500);
        String chartTitle = "FTP上传/下载测试";
        String[] lineTitles = new String[] { "FTP上传测试", "FTP下载测试" };
        List<double[]> x = new ArrayList<double[]>(2);
        List<double[]> y = new ArrayList<double[]>(2);
        x.add(ftm.getUpX());
        y.add(ftm.getUpY());
        x.add(ftm.getDwX());
        y.add(ftm.getDwY());
        int[] colors = new int[] { Color.BLUE, Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        ftpTestChartLayout.addView(lineChart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        
        new UploadResultTask().execute();
    }
    
    private class UploadResultTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            showMessage(ctx, "正在上传结果...");
        }

        @Override
        protected String doInBackground(Void... params) {
            
            if (ftpFileName == null) {
                TaskParser parser = new PullTaskParser();
                ftpFileName = parser.XmlFileCreator(task);
            }
            if (uplod(ftpFileName, ctx, ftpTestHandler)) {
                ftpFileName = null;
            }
            return ftpFileName;
        }
/*
        protected void onPostExecute(String result) {
            if (result == null) {
                showMessage(ctx, "上传成功.");
            }
        }*/
    }

}
